package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.TrackInItemWorkAdapter;
import com.glory.hikvisionmobile.adapter.TrackInWorkHintAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.bean.TrackIn.GetCarrierBean;
import com.glory.hikvisionmobile.bean.TrackIn.ItemWorkBean;
import com.glory.hikvisionmobile.bean.TrackIn.TrackInLoadBean;
import com.glory.hikvisionmobile.bean.TrackIn.XPdaCarrier;
import com.glory.hikvisionmobile.bean.TrackIn.XPdaEquipment;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Work_GraphiteBoatTrackInActivity extends BaseActivity {

    @BindView(R.id.tvLot)
    TextView tvLot;
    @BindView(R.id.tvMainWork)
    TextView tvMainWork;
    @BindView(R.id.ivMainWorkArrow)
    ImageView ivMainWorkArrow;
    @BindView(R.id.flMainWorkList)
    FrameLayout flMainWorkList;
    @BindView(R.id.etCarrier)
    FreeUI_ClearEditText etCarrier;
    @BindView(R.id.tvLotNumber)
    TextView tvLotNumber;
    @BindView(R.id.tvCurrentStep)
    TextView tvCurrentStep;
    @BindView(R.id.tvRecipe)
    TextView tvRecipe;
    @BindView(R.id.tvRQTime)
    TextView tvRQTime;
    @BindView(R.id.rvWorkHintList)
    RecyclerView rvWorkHintList;
    @BindView(R.id.tvPieceCode)
    TextView tvPieceCode;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.rvItemWorkList)
    RecyclerView rvItemWorkList;
    @BindView(R.id.llItemWorkLayout)
    LinearLayout llItemWorkLayout;
    @BindView(R.id.tvRecipeDesc)
    TextView tvRecipeDesc;

    private String lotNum;
    private FreeUI_GeneralPop codePop;
    private List<String> mainEquipmentId;
    private TrackInWorkHintAdapter trackInWorkHintAdapter;
    private TrackInItemWorkAdapter trackInItemWorkAdapter;
    private String mainQty;
    private String devices;
    private boolean isRequireEqp;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_graphite_boat_track_in;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        lotNum = bundle.getString("lotNum");
        devices = bundle.getString("devices");
        isRequireEqp = bundle.getBoolean("isRequireEqp", false);
        tvLot.setText(lotNum);
        tvMainWork.setText(devices);

        rvWorkHintList.setLayoutManager(new LinearLayoutManager(Work_GraphiteBoatTrackInActivity.this));
        rvWorkHintList.setItemAnimator(new DefaultItemAnimator());
        rvWorkHintList.addItemDecoration(new DividerItemDecoration(Work_GraphiteBoatTrackInActivity.this, 1));
        trackInWorkHintAdapter = new TrackInWorkHintAdapter(null);
        trackInWorkHintAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        trackInWorkHintAdapter.isFirstOnly(true);
        rvWorkHintList.setAdapter(trackInWorkHintAdapter);

        rvItemWorkList.setLayoutManager(new GridLayoutManager(this,2));
        rvItemWorkList.setItemAnimator(new DefaultItemAnimator());
        trackInItemWorkAdapter = new TrackInItemWorkAdapter(null);
        trackInItemWorkAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        trackInItemWorkAdapter.isFirstOnly(true);
        rvItemWorkList.setAdapter(trackInItemWorkAdapter);

        mainEquipmentId = new ArrayList<>();
    }

    @Override
    protected void initData() {
        JsonObject map = new JsonObject();
        map.addProperty("actionType", "Check");
        map.addProperty("lotId", lotNum);

        NetUtils.requestDara("HIK.PdaTrackInLoad", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<TrackInLoadBean>>(
                new TypeToken<BaseResponseBean<TrackInLoadBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<TrackInLoadBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    mainEquipmentId.clear();
                    TrackInLoadBean body = response.body().getBody();
                    tvCurrentStep.setText(body.getCurrentStepNameDesc());
                    mainQty = body.getMainQty();
                    tvLotNumber.setText(mainQty);
                    tvRQTime.setText(body.getRQTime());
                    tvRecipe.setText(body.getRecipeName());
                    tvPieceCode.setText(body.getComponentIds());
                    etCarrier.setText(body.getGraphiteCarrierId());
                    tvRecipeDesc.setText(body.getRecipeDesc());
                    List<XPdaEquipment> xPdaEquipment = body.getXPdaEquipment();
                    for (int i = 0; i < xPdaEquipment.size(); i++) {
                        mainEquipmentId.add(xPdaEquipment.get(i).getEquipmentId() + "/" + xPdaEquipment.get(i).getDescription() + "/"
                                + xPdaEquipment.get(i).getState() + "/" + xPdaEquipment.get(i).getHoldState());
                    }
                    trackInWorkHintAdapter.setNewData(body.getOperations());

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<TrackInLoadBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaTrackInLoad");

            }
        });

        if (!FreeApi_StringUtils.isEmpty(devices)){
            searchItemDevices(devices);
        }

    }


    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("石墨舟待进站");
        freeUI_titleView.setRightListener("刷新", view -> {
            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    initData();
                }
            });

        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.flMainWorkList, R.id.tvReplay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flMainWorkList:
                if (!FreeApi_StringUtils.isEmpty(devices)) {
                    return;
                }
                if (codePop != null) {
                    if (codePop.isShowing()) {
                        codePop.dismiss();
                    }
                } else {
                    codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flMainWorkList.getWidth(), mainEquipmentId, ivMainWorkArrow, (codeS, i) -> {
                        tvMainWork.setText(codeS);
                        searchItemDevices(codeS);

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivMainWorkArrow);
                codePop.showAsDropDown(flMainWorkList, 0, 0);
                break;
            case R.id.tvReplay:
                initPermission("Submit", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        if (isRequireEqp){
                            if (tvMainWork.getText().toString().length() == 0) {
                                showToast("主设备不能为空", false);
                                return;
                            }
                            int visibility = llItemWorkLayout.getVisibility();
                            if (visibility == View.VISIBLE){
                                if (FreeApi_StringUtils.isEmpty(trackInItemWorkAdapter.getItemWork())) {
                                    showToast("子设备不能为空",false);
                                    return;
                                }
                            }
                        }
                        submit();
                    }
                });

                break;
        }
    }

    private void compareCarrier(String carrierID) {
        if (FreeApi_StringUtils.isEmpty(carrierID)) {
            showToast("载具号不能为空", false);
            return;
        }

        JsonObject map = new JsonObject();
        map.addProperty("carrierId", carrierID);
        NetUtils.requestDara("HIK.PdaGetCarrier", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<GetCarrierBean>>
                (new TypeToken<BaseResponseBean<GetCarrierBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<GetCarrierBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    List<XPdaCarrier> xPdaCarriers = response.body().getBody().getxPdaCarriers();
                    String capacity = xPdaCarriers.get(0).getCapacity();
                    if (capacity.equals(mainQty)) {

                    } else {
                        showToast("载具容量和批数量不匹配", false);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<GetCarrierBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaTrackIn");
            }
        });

    }

    private void searchItemDevices(String mainWork) {
        JsonObject map = new JsonObject();
        map.addProperty("actionType","Check");
        map.addProperty("mainEquipmentId",mainWork.split("/")[0]);
        map.addProperty("lotId",lotNum);

        NetUtils.requestDara("HIK.PdaGetSubEqp", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<ItemWorkBean>>
                (new TypeToken<BaseResponseBean<ItemWorkBean>>(){}.getType(),getSupportFragmentManager(),this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ItemWorkBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    ItemWorkBean body = response.body().getBody();
                    if (body.getSubEquipmentId().size() > 0){
                        llItemWorkLayout.setVisibility(View.VISIBLE);
                        trackInItemWorkAdapter.setNewData(body.getSubEquipmentId());
                    }else {
                        llItemWorkLayout.setVisibility(View.GONE);
                        trackInItemWorkAdapter.clear();
                    }

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ItemWorkBean>> response) {
                super.onError(response);
                llItemWorkLayout.setVisibility(View.GONE);
            }
        });
    }

    private void submit() {
        DialogUtils.showLoginDialog(this, Constant.CURRENT_USER, new DialogUtils.signCallback() {
            @Override
            public void onSignSuccess() {
                JsonObject map = new JsonObject();
                map.addProperty("lotId", lotNum);
                map.addProperty("mainEquipmentId", tvMainWork.getText().toString().split("/")[0]);
                map.addProperty("durableId", etCarrier.getText().toString().trim());
                map.addProperty("subEquipmentId",trackInItemWorkAdapter.getItemWork());
                NetUtils.requestDara("HIK.PdaTrackIn", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>
                        (new TypeToken<BaseResponseBean<?>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<?>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            showConfirmDialog(Work_GraphiteBoatTrackInActivity.this, "进站成功");
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<?>> response) {
                        super.onError(response);
                        loadError(response.getException(), "HIK.PdaTrackIn");
                    }
                });
            }
        }, getSupportFragmentManager());
    }

}
